home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / doc / python-rdflib / examples / example.py next >
Encoding:
Python Source  |  2007-04-04  |  1.7 KB  |  59 lines

  1. import logging
  2.  
  3. # Configure how we want rdflib logger to log messages
  4. _logger = logging.getLogger("rdflib")
  5. _logger.setLevel(logging.DEBUG)
  6. _hdlr = logging.StreamHandler()
  7. _hdlr.setFormatter(logging.Formatter('%(name)s %(levelname)s: %(message)s'))
  8. _logger.addHandler(_hdlr)
  9.  
  10. from rdflib.Graph import Graph
  11. from rdflib import URIRef, Literal, BNode, Namespace
  12. from rdflib import RDF
  13.  
  14. store = Graph()
  15.  
  16. # Bind a few prefix, namespace pairs.
  17. store.bind("dc", "http://http://purl.org/dc/elements/1.1/")
  18. store.bind("foaf", "http://xmlns.com/foaf/0.1/")
  19.  
  20. # Create a namespace object for the Friend of a friend namespace.
  21. FOAF = Namespace("http://xmlns.com/foaf/0.1/")
  22.  
  23. # Create an identifier to use as the subject for Donna.
  24. donna = BNode()
  25.  
  26. # Add triples using store's add method.
  27. store.add((donna, RDF.type, FOAF["Person"]))
  28. store.add((donna, FOAF["nick"], Literal("donna", lang="foo")))
  29. store.add((donna, FOAF["name"], Literal("Donna Fales")))
  30.  
  31. # Iterate over triples in store and print them out.
  32. print "--- printing raw triples ---"
  33. for s, p, o in store:
  34.     print s, p, o
  35.  
  36. # For each foaf:Person in the store print out its mbox property.
  37. print "--- printing mboxes ---"
  38. for person in store.subjects(RDF.type, FOAF["Person"]):
  39.     for mbox in store.objects(person, FOAF["mbox"]):
  40.         print mbox
  41.  
  42. # Serialize the store as RDF/XML to the file foaf.rdf.
  43. store.serialize("foaf.rdf", format="pretty-xml", max_depth=3)
  44.  
  45. # Let's show off the serializers
  46.  
  47. print "RDF Serializations:"
  48.  
  49. # Serialize as XML
  50. print "--- start: rdf-xml ---"
  51. print store.serialize(format="pretty-xml")
  52. print "--- end: rdf-xml ---\n"
  53.  
  54. # Serialize as NTriples
  55. print "--- start: ntriples ---"
  56. print store.serialize(format="nt")
  57. print "--- end: ntriples ---\n"
  58.  
  59.